import { BrowserWindow, dialog, Menu } from 'electron'
import { guID, dateFormater } from "../common.js"
import path from 'path'
import got from 'got' 
import imageType from "image-type"
import fs from "fs"
// 对结果进行加工
function processResult(data = {}, code = 200, msg = ''){
  return { data, code, msg}
}
// 获取url地址
export function getUrl(e, data){
  const {url} = data
  const win = new BrowserWindow({
    width: 500,
    height:500,
    show: false,
    webPreferences: {
      offscreen: true
    }
  })
  return new Promise((resolve, reject) => {
    win.webContents.on('did-finish-load', async () => {
      const title = win.getTitle() || ''
      try {
        const image = await win.webContents.capturePage()
        const screenShot = image.toDataURL()
        resolve(processResult({name: title, screenShot, id: guID(), url, isShow: true}))
      } catch(e) {
        resolve(processResult({}, 500, '截图失败'))
      } finally {
        win.close(); // 关闭窗口，释放资源
      }
    })
    win.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
      resolve(processResult({}, 500, '您输入的网址无法访问'))
      win.close()
    })
    win.loadURL(url)
  })
}
// 弹出提示信息
export function alertEvent(e, msg){
  dialog.showMessageBoxSync({
    message: msg,
    type: 'info',
  })
}
// 打开网址
export function openUrl(e, data){
  const {url} = data
  const win = new BrowserWindow({
    width: 1000,
    height:800,
    show: true,
  })
  return new Promise((resolve, reject) => {
    win.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
      resolve(processResult({}, 500, '您输入的网址无法访问'))
      win.close()
    })
    win.loadURL(url)
    win.webContents.openDevTools() // 临时打开开发者工具
    win.webContents.executeJavaScript(`
      const btn = document.createElement('div');
      btn.id = 'button'
      btn.innerHTML = '关闭窗口'
      btn.style="position:absolute; z-index:100000;top:100px;left:100px;padding:10px;width:200px;background:pink;color:#fff;"
      document.body.appendChild(btn)
    `)
    win.webContents.on('context-menu', (e, args) => {
      if(args.srcURL) {
        const contextMenu = Menu.buildFromTemplate([
          {
            label: '图片另存为：', 
            click: () => {
              got.get(args.srcURL).then(async response => {
                console.log(response)
                const chunk = Buffer.from(response.rawBody)
                const __dirname = path.resolve();
                // 获取文件名
                const imgType = await imageType(chunk)
                const fileName = `${dateFormater('YYYYMMDDhhmmss', new Date())}.${imgType.ext}`
                const result = await dialog.showSaveDialog({
                  title: '图片另存为',
                  defaultPath: path.resolve(__dirname, './public/uploads/', fileName)
                })
                const {filePath, canceled} = result
                if(!canceled) {
                  // console.log(filePath)
                  fs.writeFileSync(filePath, chunk)
                }
                // console.log(result)
              }).catch(e => console.log(e))
            },
            accelerator: 'CommandOrControl+S'
          }
        ])
        contextMenu.popup()
      }
    })
  })
}